home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 3922 < prev    next >
Encoding:
Text File  |  1996-08-06  |  1.6 KB  |  60 lines

  1. Path: news.wright.edu!emoyer
  2. From: emoyer@cs.wright.edu (Eric Moyer)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Random numbers in C++
  5. Date: 24 Jan 1996 19:58:24 GMT
  6. Organization: Wright State University, Dayton, OH 45435
  7. Message-ID: <4e6310$2hn@mercury.wright.edu>
  8. References: <4e07ge$me7@server1.ctc.com> <310523E6.624C@ntsrv.capacity.dk>
  9. NNTP-Posting-Host: gamma.cs.wright.edu
  10. X-Newsreader: TIN [version 1.2 PL2]
  11.  
  12. Frank Nielsen (frank.nielsen@ntsrv.capacity.dk) wrote:
  13. >Richard Kemp wrote:
  14. >> 
  15. >> Hi!!
  16. >> 
  17. >> How do you make a random number in C++. I'm not familiar with C, so if it's a C
  18. >> function that will help a lot also. Thanks!!
  19. >> 
  20. >> --
  21. >> Richard Kemp
  22.  
  23.  
  24. >Hey Richard.
  25.  
  26. >First call "C" function randomize(); at startup.
  27.  
  28. >Then every time you need a random number you call random(<max random 
  29. >number>).
  30.  
  31.  
  32. If you're not using DOS, the following calls will work:
  33.  
  34. #include <time.h>
  35. #include <stdlib.h>
  36. #include <stdio.h>
  37.  
  38. main(){
  39.     int i;
  40.     srand(time(0));
  41.  
  42.     /*To get a random number in range 0..9
  43.      *Note that because of the % distribution is not perfect, but it's
  44.      *close enough.  If you need better distribution. 
  45.      *(10*rand())/RAND_MAX will work*/
  46.     
  47.     for (i=0;i<10;++i)
  48.         printf("Random Number from 0..9: %d",rand()%10);
  49.  
  50.     return(0);
  51. };
  52.  
  53. /*Better versions of rand are probably available as random() .. check your
  54.   manual/manpages*/
  55. -- 
  56. -------------------------------------__|__-----------------------------------
  57. "A wise man once said nothing"         |        Emoyer@valhalla.cs.wright.edu
  58. ---------------------------------------| ------------------------------------
  59. GCS/M d(-+) p++@ c++++ l+ u++ e+(*) m++@ s+/ !n h--(*) f+ g+ w+++ t@ r+@ !y 
  60.